package com.sc.nft.dao;


import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sc.nft.annotation.MetagoBackupDS;
import com.sc.nft.entity.EcologyPoolSourceDetail;
import com.sc.nft.mapper.EcologyPoolSourceDetailMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;

import java.util.Date;
import java.util.List;

/**
 * 重构策略：主表保留10天数据，同步数据到备份库，后台查询走备份库
 *
 * @author PC
 * @description 针对表【sc_ecology_pool_source_detail(生态池-生态熔炼积分-积分明细)】的数据库操作Dao
 * @createDate 2024-07-20 11:27:02
 */
@Slf4j
@Repository
@RequiredArgsConstructor
public class EcologyPoolSourceDetailDao {

    private final EcologyPoolSourceDetailDaoAdapter adapter;

    @Repository
    public static class EcologyPoolSourceDetailDaoAdapter extends ServiceImpl<EcologyPoolSourceDetailMapper, EcologyPoolSourceDetail> {

    }

    @MetagoBackupDS
    public Page<EcologyPoolSourceDetail> sourceDetailPage(Page<EcologyPoolSourceDetail> page, Date linkDate) {
        LambdaQueryWrapper<EcologyPoolSourceDetail> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(EcologyPoolSourceDetail::getLinkDate, linkDate);
        queryWrapper.orderByAsc(EcologyPoolSourceDetail::getId);
        return adapter.page(page, queryWrapper);
    }

    /**
     * 定时任务将 released=0 数据改为 released=1，定时任务每天04:00运行，即 released=0 的数据不超过2天
     */
    public List<EcologyPoolSourceDetail> getLeDateList() {
        LambdaQueryWrapper<EcologyPoolSourceDetail> wrapper = Wrappers.lambdaQuery();
        wrapper.le(EcologyPoolSourceDetail::getLinkDate, DateUtil.date());
        wrapper.eq(EcologyPoolSourceDetail::getReleased, Boolean.FALSE);
        return adapter.list(wrapper);
    }

    public void batchPool(List<EcologyPoolSourceDetail> detaiList) {
        adapter.saveBatch(detaiList);
    }

    public void releasedSuccess(Long id) {
        LambdaUpdateWrapper<EcologyPoolSourceDetail> wrapper = Wrappers.lambdaUpdate();
        wrapper.eq(EcologyPoolSourceDetail::getId, id);
        wrapper.set(EcologyPoolSourceDetail::getReleased, Boolean.TRUE);
        adapter.update(wrapper);
    }

}
